import { css } from "@emotion/css";
import {
  Breadcrumb,
  Button,
  Form,
  Input,
  Message,
  Popconfirm,
  Select,
  Space,
  Table,
  Tooltip,
} from "@arco-design/web-react";
import { useEffect, useState } from "react";
import { usePagination } from "../../hooks/usePagination.ts";
import { useAPI } from "../../hooks/useAPI.ts";
import { Link } from "../../components/Link";
import { BuildingAdminModal } from "../../components/BuildingAdminModal";
import {
  Role,
  SystemUserData,
  SystemUserDataRow,
} from "../../api/types/system-user.ts";
import {
  IconDelete,
  IconPen,
  IconRefresh,
  IconRight,
  IconUserAdd,
} from "@arco-design/web-react/icon";
import { EditUserInfoModal } from "../../components/EditUserInfoModal";

export default function UserManagement() {
  const api = useAPI();
  const { pagination, pageNum, pageSize, setTotal } = usePagination();
  const [formRef] = Form.useForm();
  const [userData, setUserData] = useState<SystemUserDataRow>();
  const [isOpenAddUserModal, setIsOpenAddUserModal] = useState(false);
  const [isOpenUpdateUserModal, setIsOpenUpdateUserModal] = useState(false);
  const [searchValues, setSearchValues] = useState("");
  // const [roleList, setRoleList] = useState<any[]>([]);
  const [roleId, setRoleId] = useState<any>("");
  const [data, setData] = useState<SystemUserData>();
  const [isLoading, setIsLoading] = useState(true);
  const [refresh, setRefresh] = useState(false);

  // useEffect(() => {
  //   api.getSystemRoleList({ roleName: "" }).then((response) => {
  //     setRoleList(response.data.data.rows);
  //   });
  // });

  useEffect(() => {
    setIsLoading(true);
    const values = { key: searchValues ?? "", roleIds: roleId ?? null };
    api
      .getSystemUserList_({
        ...values,
        pageNum,
        pageSize,
      })
      .then((response) => {
        response.data.data.rows = response.data?.data.rows.map(
          (row: any, index: number) => ({
            index: index + 1 + (pageNum - 1) * pageSize, // Add index starting from 1
            ...row,
          }),
        );
        setTotal(response.data?.data.total || 0);
        setData(response.data.data);
        setIsLoading(false);
      })
      .catch((error) => {
        if (error instanceof Error) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      });
  }, [pageNum, pageSize, searchValues, roleId, refresh]);

  return (
    <div>
      <BuildingAdminModal
        visible={isOpenAddUserModal}
        onClose={() => {
          setIsOpenAddUserModal(false);
        }}
        title="添加用户信息"
        onSuccess={() => {
          setIsOpenAddUserModal(false);
          setRefresh(!refresh);
        }}
      />

      <EditUserInfoModal
        visible={isOpenUpdateUserModal}
        defaultData={userData}
        onClose={() => {
          setIsOpenUpdateUserModal(false);
        }}
        title="编辑用户信息"
        isEdit={true}
        isEditPassword={true}
        isEditElder={userData?.roles[0]?.roleId === 2}
        isEditBuilding={false}
        onSuccess={() => {
          setIsOpenUpdateUserModal(false);
          setRefresh(!refresh);
        }}
      />

      <Breadcrumb
        className={css`
          padding: 12px;
          border-radius: 1px;
          font-weight: bold;
          border-left: 5px solid rgb(var(--primary-6));
          margin-bottom: 20px;
        `}
        separator={<IconRight />}
      >
        <Breadcrumb.Item style={{ fontWeight: 400 }}>
          <Link
            to="/homepage/userList"
            style={{
              textDecoration: "none",
              transition: "color 0.3s",
              fontWeight: "bold",
              fontSize: "15px",
            }}
          >
            用户管理
          </Link>
        </Breadcrumb.Item>
      </Breadcrumb>

      <div
        className={css`
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
        `}
      >
        <Form form={formRef} layout="inline" className={css``}>
          <Form.Item field="key" label="搜索：">
            <Input.Search
              value={searchValues}
              placeholder="请输入关键字"
              onChange={(value) => setSearchValues(value)}
              allowClear
              style={{ width: "200px" }}
            />
          </Form.Item>

          <Form.Item label="按用户角色查询：" field="userId">
            {/* <Select
              style={{ width: "200px" }}
              placeholder="请选择用户角色"
              allowClear
              options={roleList?.map((v: any) => ({
                label: v.roleName,
                value: v.roleId,
              }))}
              
              onChange={(value) => {
                setRoleId(value);
                setRefresh(!refresh);
              }}
            /> */}
            <Select
              placeholder="请选择用户角色"
              style={{ width: "200px" }}
              allowClear
              onChange={(value) => {
                setRoleId(value);
                setRefresh(!refresh);
              }}
            >
              <Select.Option value={Role.CommunityLeader}>
                医院办公室
              </Select.Option>
              <Select.Option value={Role.Control}>总值班</Select.Option>
              <Select.Option value={Role.BuildingAdmin}>护理部</Select.Option>
              <Select.Option value={Role.ElderUser}>长辈</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                setSearchValues("");
                setRefresh(!refresh);
              }}
            >
              <IconRefresh />
              重置
            </Button>
          </Form.Item>
        </Form>
        <Button
          type="primary"
          size="small"
          onClick={(e) => {
            e.preventDefault();
            setIsOpenAddUserModal(true);
          }}
        >
          <IconUserAdd />
          添加用户
        </Button>
      </div>

      <Table
        data={data?.rows}
        loading={isLoading}
        pagination={pagination}
        rowKey="index"
        className={css`
          margin-top: 16px;
        `}
        columns={[
          {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            sorter: (a, b) => a.index - b.index,
          },
          {
            title: "用户ID",
            dataIndex: "userId",
            key: "userId",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "用户姓名",
            dataIndex: "nickName",
            key: "nickName",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "用户角色",
            dataIndex: "roles",
            key: "roles",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (roles) => roles[0]?.roleName || "-",
          },
          {
            title: "操作",
            dataIndex: "userId",
            key: "actions",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record, row) => (
              <Space>
                <Tooltip content="编辑">
                  <Button
                    size="small"
                    shape="circle"
                    type="outline"
                    icon={<IconPen />}
                    onClick={(e) => {
                      e.preventDefault();
                      setUserData(row);
                      setIsOpenUpdateUserModal(true);
                    }}
                  />
                </Tooltip>
                <Popconfirm
                  focusLock
                  title="请确认"
                  content="是否删除该用户？"
                  onOk={async () => {
                    await api.deleteSystemUser(record);
                    setRefresh(!refresh);
                  }}
                >
                  <Tooltip content="删除">
                    <Button
                      size="small"
                      shape="circle"
                      type="outline"
                      icon={<IconDelete />}
                    />
                  </Tooltip>
                </Popconfirm>
              </Space>
            ),
          },
        ]}
      />
    </div>
  );
}
